package com.itheima.app.manager;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.itheima.app.interceptor.UserHolder;
import com.itheima.autoconfig.oss.OssTemplate;
import com.itheima.domain.db.UserInfo;
import com.itheima.domain.mongo.FocusUser;
import com.itheima.domain.mongo.Video;
import com.itheima.domain.vo.PageBeanVo;
import com.itheima.domain.vo.VideoVo;
import com.itheima.service.db.UserInfoService;
import com.itheima.service.mongo.FocusUserService;
import com.itheima.service.mongo.VideoService;
import com.itheima.util.ConstantUtil;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Component
public class VideoManager {

    @Reference
    VideoService videoService;

    @Reference
    UserInfoService userInfoService;

    @Autowired
    OssTemplate ossTemplate;

    @Autowired
    FastFileStorageClient client;

    @Autowired
    FdfsWebServer server;

    @Reference
    FocusUserService focusUserService;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Cacheable(value = "tanhua-video",key = "#userId+'_'+#pageNum+'_'+#pageSize")
    public PageBeanVo findRecommendVideoByPage(int pageNum, int pageSize, Long userId) {
        //1.调用service查询推荐给我的视频分页数据
        PageBeanVo page = videoService.findByPage(pageNum, pageSize, userId);

        //2.获取推荐视频集合,遍历它
        List<Video> items = (List<Video>) page.getItems();

        //3.封装VideoVo集合
        //3.0 创建VideoVoList
        List<VideoVo> videoVoList = new ArrayList<>();

        //3.1 遍历视频集合
        if (CollUtil.isNotEmpty(items)) {
            for (Video video : items) {
                //3.2 获取视频发布者信息
                UserInfo userInfo = userInfoService.findById(video.getUserId());

                //3.3 封装vo对象
                VideoVo videoVo = new VideoVo();

                //先封装用户,再封装视频
                BeanUtil.copyProperties(userInfo,videoVo);
                BeanUtil.copyProperties(video,videoVo);

                //封装其他字段
                videoVo.setUserId(video.getUserId());
                videoVo.setCover(video.getPicUrl());//封面
                videoVo.setSignature(video.getText());//视频文字说明

                videoVo.setHasLiked(0);//暂时设置为不点赞
                //videoVo.setHasFocus(0);//暂时设置为不关注用户

                //判断当前用户是否关注了视频的发布者
                if (stringRedisTemplate.hasKey(StrUtil.format(ConstantUtil.FOCUS_USER,userId,video.getUserId()))) {
                    videoVo.setHasFocus(1);
                }else {
                    videoVo.setHasFocus(0);
                }

                //3.4 将vo放入voList中
                videoVoList.add(videoVo);
            }
        }


        //4.将新的集合设置给pageBeanVo
        page.setItems(videoVoList);

        //5.返回分页对象
        return page;
    }

    //@CacheEvict(value = "tanhua-video",allEntries = true)
    @CacheEvict(value = "tanhua-video",key = "#userId+'_*'")
    public void save(MultipartFile videoThumbnail, MultipartFile videoFile, Long userId) throws IOException {
        //1.保存封面到oss上,返回url
        String picUrl = ossTemplate.upload(videoThumbnail.getOriginalFilename(), videoThumbnail.getInputStream());

        //2.保存视频到fastDFS上,返回url
        StorePath storePath = client.uploadFile(videoFile.getInputStream(), videoFile.getSize(), FileUtil.extName(videoFile.getOriginalFilename()), null);
        String videoUrl = server.getWebServerUrl()+storePath.getFullPath();

        //3.封装video
        Video video = new Video();
        video.setCreated(System.currentTimeMillis());
        video.setUserId(userId);
        video.setText("向幸福出发");

        video.setPicUrl(picUrl);
        video.setVideoUrl(videoUrl);

        //4.调用service完成保存操作
        videoService.save(video);
    }

    public ResponseEntity focusUser(Long focusUserId) {
        //1.获取当前用户id
        Long userId = UserHolder.get().getId();

        //2.封装关注用户
        FocusUser focusUser = new FocusUser();
        focusUser.setFocusUserId(focusUserId);
        focusUser.setUserId(userId);
        focusUser.setCreated(System.currentTimeMillis());

        //3.调用service完成保存操作
        focusUserService.saveFocusUser(focusUser);

        //4.往redis中记录关注标识
        // focus_user:当前用户id_被关注的用户id
        stringRedisTemplate.opsForValue().set(StrUtil.format(ConstantUtil.FOCUS_USER,userId,focusUserId),"1");

        return ResponseEntity.ok(null);
    }

    public ResponseEntity unFocusUser(Long focusUserId) {
        //1.获取当前用户id
        Long userId = UserHolder.get().getId();

        //2.调用service完成删除操作
        focusUserService.deleteFocusUser(userId,focusUserId);

        //3.从redis中移除关注标识
        stringRedisTemplate.delete(StrUtil.format(ConstantUtil.FOCUS_USER,userId,focusUserId));

        return ResponseEntity.ok(null);
    }
}
